package com.jiyi.activity.mine;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jauker.widget.BadgeView;
import com.jiyi.activity.AboutMeActivity;
import com.jiyi.activity.MyMessageActivity;
import com.jiyi.activity.PerfectInformation;
import com.jiyi.activity.cssz.CsszOwnerInfoActivity;
import com.jiyi.activity.zone.PersonInfoActivity;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.RefreshHintEvent;
import com.jiyi.event.UserInfoEvent;
import com.jiyi.service.MessageService;
import com.jiyi.service.impl.MessageServiceImpl;
import com.jiyi.activity.WebActivity;
import com.swift.base.ApplicationBase;
import com.swift.base.ApplicationListener.OnPostExecutedListener;
import com.swift.base.WebApiBase;
import com.swift.maintenance.R;
import com.swift.maintenance.activity.ProductActivity;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.GlideUtil;
import com.swift.widget.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MineFragment extends Fragment{

	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.civLogo)
	CircleImageView civLogo;
	
	@BindView(R.id.tvName)
	TextView tvName;
	@BindView(R.id.tvSexAge)
	TextView tvSexAge;
	@BindView(R.id.tvSign)
	TextView tvSign;
	@BindView(R.id.tvCompany)
	TextView tvCompany;
	@BindView(R.id.rlHead)
	RelativeLayout rlHead;
	@BindView(R.id.rlWSGSZL)
	RelativeLayout rlWSGSZL;
	
	@BindView(R.id.ivSystem)
	ImageView ivSystem;
	@BindView(R.id.ivWeiBao)
	ImageView ivWeiBao;
	
	BadgeView bvSystem,bvWeiBao;
	
	
	String id = UserInfoUtil.getCurrentUserId()+"";
	
	MessageService mMessageService ;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_mine, container, false);
		ButterKnife.bind(this,view);
		init();
		return view;
	}
	
	
	@Subscribe
	public void onRefreshInfo(UserInfoEvent userInfoEvent)
	{
		if (!TextUtils.isEmpty(userInfoEvent.zoneHaoYouBean.getHead_path())) {
			GlideUtil.load(this.getContext(), userInfoEvent.zoneHaoYouBean.getHead_path(), civLogo);
		}

		if (!TextUtils.isEmpty(userInfoEvent.zoneHaoYouBean.getName()) && !tvName.getText().toString().equals(userInfoEvent.zoneHaoYouBean.getName()))
		{
			tvName.setText(userInfoEvent.zoneHaoYouBean.getName());
		}
	}
	
	@Subscribe(threadMode=ThreadMode.MAIN)
	public void onRefreshHint(RefreshHintEvent refreshHintEvent) {
		int type = refreshHintEvent.type;
		switch (type) {
		case RefreshHintEvent.MIME:
			reciveMessage();
			break;

		default:
			break;
		}

	}
	
	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	/**   
	 * @author: HYM 
	 * @Title: init   
	 * @Description: TODO(这里用一句话描述这个方法的作用)    void 
	 * @date: 2017-7-18
	 */  
	private void init() {
		setTop();
		setUserInfo();
		setMenu();
		mMessageService = new MessageServiceImpl();
		reciveMessage();
		EventBus.getDefault().register(this);
	}

	/**   
	 * @author: HYM 
	 * @Title: reciveMessage   
	 * @Description: TODO(接收系统消息)    void 
	 * @date: 2017-7-27
	 */  
	private void reciveMessage() {
		if (bvSystem == null) {
			bvSystem = new BadgeView(getContext());
			bvSystem.setBadgeGravity(Gravity.TOP | Gravity.RIGHT);
			bvSystem.setTargetView(ivSystem);
		}
		if (bvWeiBao == null) {
			bvWeiBao = new BadgeView(getContext());
			bvWeiBao.setBadgeGravity(Gravity.TOP | Gravity.RIGHT);
			bvWeiBao.setTargetView(ivWeiBao);
		}
		
		int size = mMessageService.getUnReadLocalMsg(UserInfoUtil.getCurrentUserAccount()).size();
		if(size > 0)
		{
			bvSystem.setBadgeCount(size);
		}
		else 
		{
			bvSystem.setVisibility(View.GONE);
		}
		
		
//		bvWeiBao.setBadgeCount(99);
	}

	/**   
	 * @author: HYM 
	 * @Title: setMenu   
	 * @Description: TODO(部分菜单分角色显示与隐藏)    void 
	 * @date: 2017-7-27
	 */  
	private void setMenu() {
		if (UserInfoUtil.getCurrentUserRole() == AppConfig.MTN_UNIT_EMP || UserInfoUtil.getCurrentUserRole() == AppConfig.GENERAL_USER || UserInfoUtil.getCurrentUserRole() == AppConfig.ORG_MNG || UserInfoUtil.getCurrentUserRole() == AppConfig.ORG_LEADER ) {
			rlWSGSZL.setVisibility(View.GONE);
		}
	}

	/**   
	 * @author: HYM 
	 * @Title: setTop   
	 * @Description: TODO(这里用一句话描述这个方法的作用)    void 
	 * @date: 2017-7-18
	 */  
	private void setTop() {
		tvBack.setVisibility(View.GONE);
		tvTitle.setText("我");
	}
	
	
	@OnClick({R.id.rlAQPX,R.id.rlWSGSZL, R.id.rlWSGRXX,R.id.rlGYWM,R.id.rlMMXG,R.id.rlCPJS,R.id.rlTCXT,R.id.rlHead,R.id.ivSystem,R.id.ivWeiBao
		,R.id.rlWDOA})
	public void onClick(View view) {
		Intent intent = null;
		Builder builder = null;
		switch (view.getId()) {
		case R.id.rlAQPX:
			intent = new Intent(getContext(),WebActivity.class);
			intent.putExtra("title", "安全培训");
			intent.putExtra("isHideTitle", true);
			intent.putExtra("url", AppConfig.TEXT_HOST + "/Train/Index/app_main/account/" + UserInfoUtil.getCurrentUserAccount() + "/password/" + UserInfoUtil.getCurrentUserPassword()+"/access_token/"+UserInfoUtil.getCurrentUserAccessToken());
			startActivity(intent);
//			setFragment(new TrainFragment(), "Train");
			break;
		case R.id.rlWSGSZL:
			AppConfig.setSelectCompanyId(UserInfoUtil.getCurrentUserDepartId());
			intent = new Intent(getContext(),CsszOwnerInfoActivity.class);
			startActivity(intent);
			break;
		case R.id.rlWSGRXX:
			startActivity(new Intent(getActivity(),PerfectInformation.class));
			break;
		case R.id.rlGYWM:
			if(!ApplicationBase.checkNetworkAvailable()){
				Toast.makeText(this.getContext(), "离线状态不允许操作", Toast.LENGTH_LONG).show();
				return;
			}
			intent = new Intent(getActivity(),AboutMeActivity.class);
			startActivity(intent);
			break;
		case R.id.rlMMXG:
			if(!ApplicationBase.checkNetworkAvailable()){
				Toast.makeText(this.getContext(), "离线状态不允许修改密码", Toast.LENGTH_LONG).show();
				return;
			}
	    	   	
			LayoutInflater inflater = this.getActivity().getLayoutInflater();
			final View layout = inflater.inflate(R.layout.layout_changepassword, null,  false);
			builder = new Builder(getContext());
			builder.setTitle("密码修改");
			builder.setView(layout);
			builder.setPositiveButton("确认", null);		
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}			
			});
			
			final AlertDialog alertDialog = builder.create();
			alertDialog.show();
			
			alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new OnClickListener() {
		      @Override
			    public void onClick(View v) {
		    	    String access_token = ApplicationBase.LocalData.getString(AppConfig.ACCESS_TOKEN, "");
					String password = ((EditText)layout.findViewById(R.id.edt_lgoin_password)).getText().toString();
					String newPassword = ((EditText)layout.findViewById(R.id.edt_new_password)).getText().toString();
					String newPassword1 = ((EditText)layout.findViewById(R.id.edt_new_password1)).getText().toString();
					if (!newPassword1.equals(newPassword)){
						ToastUtil.getInstances().showMsg("确认密码不符！");
					}else{
						 AppBase.WebClient.changePassword(password, newPassword,access_token, new OnPostExecutedListener() {						
							@Override
							public void postExecuted(int tag, Object result) {
								ToastUtil.getInstances().showMsg(result.toString());
								if (tag == WebApiBase.API_SUCCESS_CODE){
									alertDialog.dismiss();
								}
							}
						});
					}
			      }
		    });
			break;
		case R.id.rlCPJS:
			intent = new Intent(getContext(),ProductActivity.class);
			startActivity(intent);
			break;
		case R.id.rlTCXT:
			builder = new Builder(getContext());
			builder.setMessage("确认注销？");
			builder.setTitle("提示");
			builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {			
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//清除环信登录
					UserHelp.getInstance().clearUser(getActivity(), true);
				}
			});
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
				
			});
			builder.create().show();	
			break;
		case R.id.rlHead:
			intent = new Intent(getActivity(),PersonInfoActivity.class);
			intent.putExtra("id", UserInfoUtil.getCurrentUserId()+"");
			startActivity(intent);
			break;
		case R.id.ivSystem:
			intent = new Intent(getActivity(),MyMessageActivity.class);
			startActivity(intent);
//			intent = new Intent(getActivity(),ReadTextActivity.class);
//			startActivity(intent);
			break;
		case R.id.ivWeiBao:
			String url = "";
			if (UserInfoUtil.getCurrentUserDepartType() == 0) {
				//监管
				url = AppConfig.TEXT_HOST + "/Supervise/Mail/app_sjx/account/" + UserInfoUtil.getCurrentUserAccount() + "/password/" + UserInfoUtil.getCurrentUserPassword()+"/access_token/"+UserInfoUtil.getCurrentUserAccessToken();
			}
			else if (UserInfoUtil.getCurrentUserDepartType() == 1) {
				//业主
				url = AppConfig.TEXT_HOST + "/Owner/Message/app_reMessageList/account/" + UserInfoUtil.getCurrentUserAccount() + "/password/" + UserInfoUtil.getCurrentUserPassword()+"/access_token/"+UserInfoUtil.getCurrentUserAccessToken();
			}
			else if (UserInfoUtil.getCurrentUserDepartType() == 6) {
				//维保
				url = AppConfig.TEXT_HOST + "/Wap/Message/app_recivemessage/account/" + UserInfoUtil.getCurrentUserAccount() + "/password/" + UserInfoUtil.getCurrentUserPassword()+"/access_token/"+UserInfoUtil.getCurrentUserAccessToken();
			}
			else {
				return;
			}
			
			
			intent = new Intent(getContext(),WebActivity.class);
			intent.putExtra("title", "维保信件");
			intent.putExtra("isHideTitle", true);
			intent.putExtra("url", url);
			startActivity(intent);
			break;
		case R.id.rlWDOA:
			intent = new Intent(getContext(),WebActivity.class);
			intent.putExtra("title", "进销存");
			intent.putExtra("isHideTitle", true);
			intent.putExtra("url", AppConfig.TEXT_HOST + "/EnterSellSave/JxcAccount/app_index/account/" + UserInfoUtil.getCurrentUserAccount() + "/password/" + UserInfoUtil.getCurrentUserPassword()+"/access_token/"+UserInfoUtil.getCurrentUserAccessToken());
			startActivity(intent);
			break;
		default:
			break;
		}
	}
	/**   
	 * <p>Title: getContext</p>   
	 * <p>Description: </p>   
	 * @return   
	 * @see Fragment#getContext()
	 */ 
	@Override
	public Context getContext() {
		return super.getContext();
	}
	
	/**   
	 * @author: HYM 
	 * @Title: setUserInfo   
	 * @Description: TODO(设置用户的个人信息)    void 
	 * @date: 2017-7-27
	 */  
	void setUserInfo()
	{
		GlideUtil.load(getContext(),
				UserInfoUtil.getCurrentUserLogo(),
				civLogo);

		tvCompany.setText(UserInfoUtil.getCurrentUserDepartName());
		tvName.setText(UserInfoUtil.getCurrentUserName());
		tvSign.setText("");
		tvSexAge.setText("");
	}
	
	//在当前的我的里面显示，但是我感觉这样的体验也不是特别好
//	private void setFragment(Fragment fragment, String tag) {
//		FragmentManager fm = getActivity().getSupportFragmentManager();
//		FragmentTransaction transaction = fm.beginTransaction();
//		transaction.setCustomAnimations(R.anim.push_left_in,
//				R.anim.push_left_out);
//		transaction.replace(R.id.id_container, fragment, tag);
//		transaction.commit();
//	}
}
